package com.qxgltj.qxgl.service;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.qxgltj.qxgl.dao.IRolesDao;
import com.qxgltj.qxgl.dto.RolesDTO;
import com.qxgltj.qxgl.model.Roles;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class RolesServiceImpl implements IRolesService {
    @Resource
    private IRolesDao rolesDao;

    @Override
    public Page<Roles> finPage(RolesDTO dto) {
        Sort.Order order = new Sort.Order(Sort.Direction.ASC, "Id");
        PageRequest request = PageRequest.of((dto.getPage() - 1) * dto.getLimit(), dto.getLimit(), Sort.by(order));
        return rolesDao.findAll(getSpec(dto), request);
    }

    private Specification<Roles> getSpec(final RolesDTO dto) {
        return new Specification<Roles>() {

            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Roles> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
              Predicate p =criteriaBuilder.conjunction();
              List<Expression<Boolean>> exList=p.getExpressions();
              if (dto.getName()!=null&&!"".equals(dto.getName())) {
                exList.add(criteriaBuilder.like(root.get("name"),"%"+dto.getName()+"%"));
                System.out.println("条件判断不为空");
            }
                return p;
            }
        };
    }

    @Override
    public Roles saveRoles(Roles r) {
        return rolesDao.save(r);
    }

    @Override
    public void del(String id) {
        rolesDao.deleteById(id);
    }

}